<template>
  <el-dialog
    :model-value="isShowDialog"
    :title="title"
    :width="width"
    min-width="500px"
    :close-on-click-modal="false"
    :before-close="handleModalClose"
  >
    <div class="main_block">
      <el-row>
        <el-col :span="12">
          <div class="header_item flex_block">
            <div class="text">测试时间：</div>
            <el-date-picker
              style="width: 220px"
              v-model="params.time"
              type="datetime"
              placeholder="不填默认立即执行"
              :clearable="false"
              :show-now="false"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="header_item flex_block">
            <div class="text">并发数：</div>
            <el-input
              min="1"
              @blur="handleBlurConcurrency"
              v-model.trim="params.concurrency"
              type="number"
              placeholder="请输入并发数"
              style="width: 220px"
            ></el-input>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-if="showPriority">
          <div class="header_item flex_block">
            <div class="text">优先级：</div>
            <el-select
              v-model="params.priority"
              @change="handleChangePriority"
              multiple
              placeholder="请选择优先级"
              style="width: 220px"
            >
              <el-option
                class="select_item"
                v-for="item in priority_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="header_item flex_block">
            <div class="text">执行环境：</div>
            <el-select
              v-model="params.environment"
              placeholder="请选择执行环境"
              style="width: 220px"
            >
              <el-option
                class="select_item"
                v-for="item in environmentList"
                :key="item.envName"
                :label="item.envName"
                :value="item.envName"
              />
            </el-select>
          </div>
        </el-col>
      </el-row>
      <div class="table_block">
        <el-table
          :data="tableData"
          border
          :style="{ height: 'calc(100vh - 420px)' }"
        >
          <el-table-column prop="name" label="用例名" min-width="180" />
          <el-table-column prop="severity" label="优先级" min-width="180" />
          <el-table-column
            prop="caseData"
            label="测试数据"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <el-select
                v-model="row.isDefaultId"
                placeholder="测试数据"
                size="small"
                style="min-width: 100px"
              >
                <el-option
                  class="select_item"
                  v-for="item in row.dataList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center"
            v-if="showDelete"
          >
            <template #default="scope">
              <div class="flex_block_center">
                <el-icon
                  class="color_delete cursor_pointer"
                  @click="handleDeleteCase(scope.row, scope.$index)"
                  ><Delete
                /></el-icon>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleModalClose">取消</el-button>
        <el-button type="primary" @click="handleModalConfirm"> 执行 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { formatTime } from "@/utils/index.js";
import { PriorityAllList } from "@/api/test_case.js";
import { AdminEnvironmentList } from "@/api/settings.js";
import { ElMessage } from "element-plus";
const props = defineProps({
  isShowDialog: { type: Boolean, default: false },
  title: { type: String, default: "发起测试" },
  width: { type: [String, Number], default: "800px" },
  list: { type: Array, default: () => [] },
  showPriority: { type: Boolean, default: false }, //是否显示优先级
  showDelete: { type: Boolean, default: true }, //是否显示删除功能
});
const environmentList = ref([]); //环境

const $emit = defineEmits(["close", "confirm"]); // 接受父组件传递的 方法

const params = reactive({
  // 顶部可选 参数
  time: formatTime(), //默认当前时间
  concurrency: 1,
  priority: [],
  environment: null,
});
let originally_environment = null; //备份初始数据（执行环境）默认第一个

const priority_options = ref([]); // 优先级下拉框数据列表
const tableData = ref([]); //table数据
const flatCaseData = ref([]); //备份列表数据

// 组件加载时
onMounted(() => {
  getEnvironmentData();
});

watch(
  () => props.list,
  (val) => {
    console.log("监听到 list 参数", val);
    if (val && val.length && val.length > 0) {
      let list = JSON.parse(JSON.stringify(val));
      list.forEach((item) => {
        if (item.dataList && item.dataList.length) {
          // 如果有默认的 测试数据 就拿默认的测试数据
          const file = item.dataList.find((value) => value.isDefault == 1);
          item.isDefaultId = file?.id || "";
        } else {
          item.dataList = [];
        }
      });
      tableData.value = list;
      flatCaseData.value = JSON.parse(JSON.stringify(list));
      // 处理 优先级下拉框数据
      priority_options.value = [
        ...new Set(
          tableData.value
            .map((item) => item.severity)
            .filter((severity) => severity != null && severity != "") // 过滤null和undefined
        ),
      ].map((severity) => ({
        value: severity,
        label: severity, // 标签映射，默认转为字符串
      }));
    }
  },
  { immediate: true, deep: true }
);
// 监听 isShowDialog 变为 true 时初始化参数
watch(
  () => props.isShowDialog,
  (newVal) => {
    if (newVal) {
      params.time = ''; // 默认当前时间
      params.concurrency = 1;
      params.priority = [];
      params.environment = originally_environment;
      tableData.value = flatCaseData.value;
    }
  },
  { immediate: true }
);
// 并发数只能是正整数
const handleBlurConcurrency = () => {
  params.concurrency = parseInt(params.concurrency);
  if (params.concurrency <= 0 || isNaN(params.concurrency)) {
    params.concurrency = 1;
  }
};

// 优先级的选中 进行筛选
const handleChangePriority = () => {
  let list = [];
  params.priority.forEach((item) => {
    flatCaseData.value.forEach((val) => {
      if (item == val.severity) {
        list.push(val);
      }
    });
  });
  tableData.value = list;
  if (params.priority.length == 0) {
    tableData.value = flatCaseData.value;
  }
};

// 删除表单的数据
const handleDeleteCase = (item, index) => {
  console.log(item, index);
  ElMessageBox.confirm(`确定要取消执行"${item.name}"该用例吗？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      tableData.value.splice(index, 1);
    })
    .catch(() => {});
};

//获取执行环境数据
const getEnvironmentData = () => {
  let obj = {
    pageNum: 1,
    pageSize: 2000,
    queryParams: {},
  };
  AdminEnvironmentList(obj).then((res) => {
    environmentList.value = res.list || [];
    console.log("执行环境数据", environmentList.value);
    if (environmentList.value.length > 0) {
      const isDefault = environmentList.value.find((val) => val.default);
      if (isDefault) {
        params.environment = isDefault.envName;
        originally_environment = isDefault.envName;
      } else {
        params.environment = environmentList.value[0].envName;
        originally_environment = environmentList.value[0].envName;
      }
    }
  });
};

// 关闭弹窗
const handleModalClose = () => {
  $emit("close");
};

const handleModalConfirm = () => {
  if (!params.concurrency) {
    return ElMessage.warning("请选择并发数");
  }
  if (!params.environment) {
    return ElMessage.warning("请选择执行环境");
  }
  if (tableData.value.length === 0) {
    return ElMessage.warning("请最少选择一个用例");
  }
  // if (params.time) {
  //   // 匹配最后一个 ":数字" 并替换为 ":00"
  //   params.time = params.time.replace(/:\d{2}$/, ":00");
  // }
  // if (params.time < formatTime()) {
  //   return ElMessage.warning("执行时间不能早于当前时间");
  // }
  for (let i = 0; i < tableData.value.length; i++) {
    // 如果没选测试数据，就不让提交，提示需要选择
    if (!tableData.value[i].isDefaultId) {
      return ElMessage.warning(`${tableData.value[i].name} 需选择要测试的数据`);
    }
  }
  $emit("confirm", tableData.value, params);
  handleModalClose();
};
</script>

<style scoped lang="scss">
.header_item {
  display: flex;
  margin-bottom: 5px;
  align-items: center;
  .text {
    white-space: nowrap;
    width: 100px;
    text-align: right;
  }
}
.table_block {
  margin-top: 10px;
}
</style>
